/**
 * Copyright 2007 Jason Horman, Pete Aykroyd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.functor;

/**
 * A org.functor that takes one argument and returns no value.
 */
public abstract class UnaryProcedure<P> extends Functor {
	/** Execute this procedure. */
	public abstract void run(P object);

	public UnaryProcedure onlyIf(final UnaryPredicate predicate) {
		return predicate.ifTrue(this);
	}

	public static final UnaryProcedure NoOp = new UnaryProcedure() {
		public void run(Object obj) {
		}
	};

	public UnaryProcedure then(final UnaryProcedure doThis) {
		final UnaryProcedure me = this;
		return new UnaryProcedure() {
			public void run(Object obj) {
				me.run(obj);
				doThis.run(obj);
			}
		};
	}

	public UnaryProcedure then(final Procedure doThis) {
		final UnaryProcedure me = this;
		return new UnaryProcedure() {
			public void run(Object obj) {
				me.run(obj);
				doThis.run();
			}
		};
	}

	/**
	 * When run executes the Procedure passed with no arguments.
	 */
	public static UnaryProcedure dropAndExecute(final Procedure andExecute) {
		return new UnaryProcedure() {
			public void run(Object obj) {
				andExecute.run();
			}
		};
	}

	/**
	 * Turns a UnaryProcedure into a Procedure and binds its param to the value.
	 */
	public Procedure bind(final Object value) {
		final UnaryProcedure me = this;
		return new Procedure() {
			public void run() {
				me.run(value);
			}
		};
	}

	public static UnaryProcedure create(String expression, Class parameterType) {
		return new DynamicUnaryProcedure(expression, parameterType);
	}

}
